#!/usr/bin/perl -w
#the cut video file;
use DBI;
use mydb;
use File::Path;
use myvideo;
use Digest::MD5;
use server;
use myserver;
use Net::SCP::Expect;
use File::Basename qw<basename dirname>;
 
my_connect();
while(1) {

	$sql = "SELECT * FROM t_task WHERE status = 'prepare' order by level desc, ctime limit 10";
	$tasksth = $dbconn->prepare($sql) or die $dbconn->errstr;
	$tasksth->execute() or die "错误: " . $tasksth->errstr;
		
print "select task is OK!\n";
  	while (@data0 = $tasksth->fetchrow()) {
	
  		$rowid = $data0[0];
  		$file = $data0[5];
  		$playtime = $data[20];
  		$ip =  get_ServerIP($servername);
  		$spath = get_ServerPath($servername);

  		$spath = $spath."/$rowid";

  		rmtree($spath)||die "删除目录错误 $!";
  		mkdir($spath, 0777)||die"不能创建$spath目录";

  		@userpasswd = get_ServerUserPasswd(@servername);
  		$user = $userpasswd[0];
  		$passwd = $userpasswd[1];

  		$s_server=$data0[6];
  		#$s_ip = get_ServerIP($s_server);
  		#@userpasswd1 = get_ServerUserPasswd($s_server);
  		#$s_user = $userpasswd1[0];
  		#$s_passwd = $userpasswd1[1];

print "begin cut task !\n";
	#把文件从原服务器的位置拷贝到预处理服务器中.

#  		my $scpe = Net::SCP::Expect->new(user=>"$s_user",password=>"$s_passwd", auto_yes=>1);
#  		$scpe->scp("$s_ip:$file", "$spath");

	#对于传输的文件进行分割，首先判断是否需要分割，并把分割的结果写入到分割的任务表中。

  		$filename = basename $file;
  		$filename = "$spath\/$filename";
  		$res = `mkvmerge --split 300s $file -o $filename.%05d`; 
  		$res1 = `ls $filename.?????|wc -l`;

  		for($i = 1; $i <= $res1; $i++) {
	#分割后的内容写入到t_prepare

      			$sql = "insert into t_prepare(tid, spath, level, ctime, vcode, acode, playtime, logo, x, y, total, cur, server, cpath, status, scomment) values($rowid, \'$filename\', 5, now(), ?, ?, 300, '', 0, 0, $res1, ?, \'$servername\', ?, 'cut', '')"; 

      			$stmp1 = "0000".$i;
      			$stmp1 = substr($stmp1, length($stmp1)-5, 5);
      			$pth = $dbconn->prepare($sql) or die $dbconn->errstr;
      			$pth->execute('', '', $i,  $filename."\.".$stmp1);
  		}

	#在分割后把任务内容填加进c_control表中。
  		$sql = "insert into c_control(tid, level, total, ctime, etime) values($rowid, 5, $res1, now(), now())";
  		$pth = $dbconn->prepare($sql) or die $dbconn->errstr;
  		$pth->execute();

        	$sql = "update t_task set status = 'cut' where tid = $rowid";
        	$upsth = $dbconn->prepare($sql) or die $dbconn->errstr;
        	$upsth->execute() or die "错误: " . $upsth->errstr;

#
	}
sleep(2);
}
my_disconnect();
